#include "common.h"

using namespace std;
// server -- to read
int main() {
    // 创建一个匿名管道
    umask(0);
    int ipcfd = mkfifo(IPC_PATH, 0600); // create
    // create fifo
    if (ipcfd != 0) { 
        cerr << "mkfifo error" << endl;
        exit(1);
    }
    int fd = open(IPC_PATH, O_RDONLY); // 只读方式打开，会返回文件描述符
    if (fd < 0) {
        cerr << "open file fail" << endl;
        exit(1);
    }
    cout << " -- server launch -- " << endl;

#define LEN 1024
    char buf[LEN];
    while (true) {
        memset(buf, 0, sizeof(buf));
        // 读取 buf 缓冲区中的所有数据 len = sizeof(buf)
        ssize_t rdret = read(fd, buf, sizeof(buf));
        if (rdret > 0) { // has read
            // 去掉最后一个字符，回车
            buf[rdret] = '\0'; 
            cout << "client -> server msg: " << buf << endl;
        }
        else if (rdret == 0) {
            cout << "file closed  --->  lose connection" << endl;
            break;
        }
    }
    close(fd);

    unlink(IPC_PATH);
    return 0;
}